package com.xyhuo.leetcode.january;

import com.xyhuo.leetcode.common.ListNode;

import java.util.HashSet;
import java.util.Set;

/**
 * 环形链表Ⅱ
 * https://leetcode.cn/problems/linked-list-cycle-ii/
 *
 * @desc 应该使用快慢指针，谁TM想得到！
 * @time 2024/1/18
 */
public class DetectCycle {

    public ListNode detectCycle(ListNode head) {
        Set<ListNode> alreadySet = new HashSet<>();
        ListNode tmp = head;
        while (tmp != null) {
            if (alreadySet.contains(tmp.next)) {
                return tmp.next;
            }
            alreadySet.add(tmp);
            tmp = tmp.next;
        }
        return null;
    }
}
